import { Directive, ElementRef, Input, OnInit, OnDestroy } from '@angular/core';
//Controls
import { AmChartsService } from "@amcharts/amcharts3-angular";
import { debug } from 'util';

@Directive({
    selector: '[benchmarkChart]'
})
export class BenchmarkChartDirective implements OnInit, OnDestroy {
    private chart: any;
    private _chartData: any[];
    private arrowSet: boolean = false;

    @Input() chartID: string;
    @Input() riskLevels: any[]; //list of company subIndustry clusters
    @Input() companyName: string;
    @Input() companyRiskLevel: any; //cluster code
    @Input() showRiskLevels: boolean;
    @Input() hidePlus: boolean;
    @Input() primaryName: string;
    @Input() secondaryName: string;
    @Input() set chartData(value: any[]) {
        if (value) {
            this._chartData = value;
            if (this.chart) {
                this.AmCharts.updateChart(this.chart, () => {
                    this.chart.dataProvider = this._chartData;
                    this.chart.graphs = this.setGraphs();
                });
                //this.buildArrow(this.chart);
                //this.addCompanyCircle(this.chart);
            }
        }
    }

    constructor(private el: ElementRef, private AmCharts: AmChartsService) { }

    ngOnInit() {
        //generate chart without data. data will be added when getting the chartData
        this.chart = this.AmCharts.makeChart(this.chartID, {
            type: "serial",
            gridCount: 7,
            dataProvider: this._chartData,
            valueAxes: [{
                axisAlpha: 0,
                labelsEnabled: true,
                unit: '%',
                dashLength: 3
            }],
            gridAboveGraphs: true,
            columnSpacing: 0,
            startDuration: 0, //animation disabled because of angular2-ie9-shims making it slow
            graphs: this.setGraphs(),
            chartCursor: {
                oneBalloonOnly: true,
                categoryBalloonEnabled: false,
                cursorAlpha: 0,
                zoomable: false
            },
            categoryField: "score",
            categoryAxis: {
                hidePlus: this.hidePlus,
                autoGridCount: false,
                gridPosition: "start",
                tickPosition: "start",
                gridAlpha: 0,
                labelsEnabled: false,
                labelFunction: function (valueText, date, categoryAxis) {
                    return valueText;
                }
            },
            export: {
                enabled: false
            },
            listeners: [{
                event: "rendered",
                method: (e) => {
                    if (this.chart == undefined) this.chart = e.chart;
                    if (this.showRiskLevels) {
                        this.buildAxis(e.chart.categoryAxis.x);
                    }
                }
            },
            {
                event: "resized",
                method: (e) => {
                    if (this.showRiskLevels) {
                        this.buildAxis(e.chart.categoryAxis.x);
                    }
                }
            }]
        });

        //this.buildArrow(this.chart);
        //this.addCompanyCircle(this.chart);
    }

    ngOnDestroy() {
        this.AmCharts.destroyChart(this.chart);
    }

    private setGraphs(): any[] {
        var result: any[] = [];
        let balloonText: string = " <b>[[primary]]</b><br>";

        var primary: any = {
            balloonText: balloonText,
            showBalloon: true,
            fillAlphas: 1,
            lineAlpha: 0,
            type: "column",
            valueField: "primary"
        };

        var secondary: any = {
            showBalloon: false,
            fillColors: "#A7A9AC",
            fillAlphas: 1,
            lineAlpha: 0,
            type: "column",
            valueField: "secondary"
        }
        if (this._chartData && this._chartData.length > 0) {
            if (this._chartData[0].color)
                primary.colorField = "color";
            else
                primary.fillColors = "#F0AB01";

            if (this._chartData[0].primary !== undefined)
                result.push(primary);
            if (this._chartData[0].secondary !== undefined)
                result.push(secondary);
        }

        return result;
    }

    private buildAxis(startLocation: number): void {
        if (this.riskLevels) {
            var minInterval = 0;
            var htmlContent = '', style = '', textStyle = '', distributionTextDiv = '', distributionColorDiv = '';
            var width = this.chart.categoryAxis.stepWidth;
            var element = document.createElement('canvas');
            var context = element.getContext("2d");
            context.font = "14px Calibri";
            for (var i = 0; i < this.riskLevels.length; i++) {
                style = 'float: left;height: 100%;';
                textStyle = 'text-align: center;font-size: 8pt;margin: 0px';
                if (minInterval == 0)
                    style += 'margin-left:' + startLocation + 'px; border-left: 2px dashed white;';

                style += 'border-right: 2px dashed white;width:' + width + 'px;';

                let text = this.riskLevels[i].shortName;

                distributionTextDiv = `<p class="text-center chart-legend">${text}</p>`;

                distributionColorDiv = "<div style='background-color:" + this.riskLevels[i].color + ";height:50%;'></div>";

                htmlContent += "<div style='" + style + "'>" + distributionColorDiv + distributionTextDiv + "</div>";

                width = 0;
                minInterval = 1;

                width += this.chart.categoryAxis.stepWidth;
            }

            this.el.nativeElement.children.benchmarkChartAxis.innerHTML = htmlContent;
        }
    }

    private buildArrow(chart: any): void {
        if (chart.chartData) {
            for (var i = 0; i < chart.chartData.length; i++) {
                if (chart.chartData[i].dataContext.companyBullet == true) {
                    //get text width
                    var element = document.createElement('canvas');
                    var context = element.getContext("2d");
                    context.font = "14px Calibri";
                    this.AmCharts.updateChart(this.chart, () => {
                        //set company name
                        this.chart.allLabels = [{
                            text: this.companyName,
                            size: 10,
                            bold: true,
                            x: chart.categoryAxis.x + chart.chartData[i].x.categoryAxis - Math.floor(context.measureText(this.companyName).width / 2),
                            y: 6
                        }];

                        //set arrow
                        this.chart.trendLines = [
                            {
                                lineThickness: 1,
                                lineColor: '#000',
                                initialValue: chart.chartData[i].dataContext.primary,
                                finalValue: chart.valueAxes[0].max,
                                initialCategory: chart.chartData[i].dataContext.score,
                                finalCategory: chart.chartData[i].dataContext.score,
                                initialImage: {
                                    url: "assets/img/down-arrow.png",
                                    height: 7,
                                    width: 7,
                                    offsetY: -3
                                }
                            }
                        ];

                    });
                    break;
                }
            }
        }
    }

    private addCompanyCircle(chart: any): void {
        if (chart.chartData) {
            for (var i = 0; i < chart.chartData.length; i++) {
                if (chart.chartData[i].dataContext.companyBullet == true) {
                    this.AmCharts.updateChart(this.chart, () => {
                        // add circle 
                        this.chart.trendLines = [
                            {
                                lineThickness: 1,
                                lineColor: '#000',
                                initialValue: 0,
                                finalValue: 0,
                                initialCategory: chart.chartData[i].dataContext.score,
                                finalCategory: chart.chartData[i].dataContext.score,
                                initialImage: {
                                    url: "assets/img/icon-circle.png",
                                    height: 7,
                                    width: 7,
                                    offsetY: -3
                                }
                            }
                        ];

                    });
                    break;
                }
            }
        }
    }
}